package persistence.sale;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.Sale;

public class SaleDAOFile implements SaleDAO {

    public Map<String, Sale> saleMap = new HashMap<String, Sale>();
    private String fileName;
    private static SaleDAOFile persistenceManager = null;

    private SaleDAOFile() {
    }

    public static SaleDAO getJDBCPersistenceManager() {
        if (persistenceManager == null) {
            persistenceManager = new SaleDAOFile();
        }
        return persistenceManager;
    }

    @Override
    public boolean setUp(String url, String driver, String user, String password) {
        this.fileName = "fileName";
        try {
            File file = new File(fileName + "ventas.txt");
            if (!file.exists()) {
                return true;
            }
            InputStream inputStream = new FileInputStream(file);
            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
            int numberOfSales = (Integer) objectInputStream.readObject();
            for (int i = 0; i < numberOfSales; i++) {
                Sale sale = (Sale) objectInputStream.readObject();
                saleMap.put(sale.getId(), sale);
            }
            objectInputStream.close();
        } catch (Exception ex) {
            Logger.getLogger(SaleDAOFile.class.getName()).log(Level.SEVERE,
                    "No se pudieron cargar los datos del archivo de ventas", ex);
            return false;
        }
        return true;
    }

    @Override
    public synchronized boolean createSale(Sale sale) {
        saleMap.put(sale.getId(), sale);
        return true;
    }

    @Override
    public synchronized void readAllSales(Map<String, Sale> saleArray) {
        for (Sale sale : saleMap.values()) {
            saleArray.put(sale.getId(), sale);
        }
    }

    @Override
    public boolean disconnect() {

        try {
            OutputStream outputStreamSales = new FileOutputStream(new File(fileName + "ventas.txt"));
            ObjectOutputStream objectOutputStreamSales = new ObjectOutputStream(outputStreamSales);
            objectOutputStreamSales.writeObject(saleMap.size());
            for (Sale sale : saleMap.values()) {
                objectOutputStreamSales.writeObject(sale);
            }
            objectOutputStreamSales.close();
        } catch (IOException ex) {
            Logger.getLogger(SaleDAOFile.class.getName()).log(Level.SEVERE,
                    "No se pudieron guardar los datos en el archivo de ventas", ex);
            return false;
        }
        return true;
    }
}
